<template>
  <div class="app-container">
    <my-tree-selector-query
      ref="regionTree"
      title="部署区域"
      :current-node-key="this.filter.data.regionId"
      :default-expanded-keys="[this.filter.data.regionId]"
      :options="regionDataOptions"
      :treeProps="{ children: 'children',label: 'name'}"
      @click-node="handleNodeClick"
    />
    <div class="right-wrap">
      <u-page-config
        :filter-array="filterArray"
        v-model="filter"
        label-width="80px"
        :getList="getList"
        :tableData="tableData"
        :tableColumn="tableColumn"
        :total="total"
        :loading="loading"
        showSelection
        @handleSelectionChange="handleSelectionChange"
        @rowDetail="rowDetail"
      >
        <template #groupId="{item}">
          <treeselect
            v-model="filter.data.groupId"
            :options="groupOptions"
            :normalizer="normalizer"
            :show-count="true"
            placeholder="选择分组"
            style="width: 240px"
            noOptionsText="暂无选项"
            noResultsText="没有匹配的搜索结果"
          />
        </template>
         <template #network="{item}">
          <treeselect
                v-model="filter.data.branchCode"
                :options="branchDataOptions"
                :normalizer="branchNormalizer"
                placeholder="选择设备部署默认网点"
                style="width: 240px"
                noOptionsText="暂无选项"
                noResultsText="没有匹配的搜索结果"
              />
        </template>

        <div class="head-card-wrap" slot="head">
          <div class="card-item" v-for="item in cardList" :key="item.key" @click="handleFilterDeviceStatus(item.status)">
            <div class="name">
              <div class="circle" :style="{'background': item.color}"/>
              {{ item.name }}
            </div>
            <div class="value">{{ deviceNumData[item.key] || 0 }}<span>台</span></div>
          </div>
        </div>

        <template #btn="{row, item}">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="rowDetail(row)"
            v-hasPermi="['operationAndMonitoring:deviceMonitoring:detail']"
          >详细信息
          </el-button>
        </template>

        <template #deviceStatus="scope">
          <dict-tag
            :options="dict.type.device_status"
            :value="scope.row.deviceStatus"
          />
        </template>
      </u-page-config>
    </div>
  </div>
</template>

<script>
  import MyTreeSelectorQuery from "@/views/components/myTreeSelectorQuery";
  import table from "@/mixin/uTable";
  import UPageConfig from "@/components/uPageConfig/index";
  import UForm from "@/components/uForm/index";
  import Treeselect from "@riophae/vue-treeselect";
  import {reqGetCountDeploymentStatus, listManager} from "@/api/operationAndMonitoring/deviceMonitoring";
  import {listGroup} from "@/api/device/group";
  import {handleTree} from "@/utils/ruoyi";

  export default {
    name: "DeviceMonitoring",
    mixins: [table],
    dicts: ['device_status'],
    components: {
      UPageConfig,
      MyTreeSelectorQuery,
      Treeselect
    },
    data() {
      return {
        filter: {
          pageSize: 10,
          pageNum: 1,
          data: {
            deviceStatus: undefined
          }
        },
        filterArray: [
          {label: "部署分组", key: "groupId", type: "slot", slot: 'groupId'},
          {label: "设备状态", key: "deviceStatus", type: "select", options: [],},
          {
            label: "设备品牌", key: "brandCode", type: "select", options: [],
            props: {value: 'code', label: 'name'}
          },
          {label: "默认网点", key: "branchCode", type: "slot", slot: 'network'}
        ],
        tableColumn: [
          {label: "设备ID", prop: "deviceId"},
          {label: "设备部署名称", prop: "deploymentName"},
          {label: "部署区域", prop: "ancestorsName"},
          {label: "部署分组", prop: "groupName"},
          {label: "型号", prop: "deviceName"},
          // {label: "中间件版本", prop: "middlewareVersion"},
          {label: "状态", prop: "orderStatus", type: 'slot', slot: 'deviceStatus'},
          {label: "操作", type: "slot", attr: {width: 120}, slot: 'btn'}
        ],
        cardList: [
          {name: '符合条件设备总数', key: 'total', color: 'transparent'},
          {name: '其中正常设备', key: 'normal', status: '1', color: '#13ce66'},
          {name: '其中异常设备', key: 'error', status: '3', color: '#ffba00'},
          {name: '其中离线设备', key: 'offline', status: '2', color: '#f80f02'},
          {name: '其中已关机设备', key: 'poweroff', status: '5', color: '#c1c1c1'},
        ],
        // 分组选项
        groupOptions: [],
        // 各种设备状态数量
        deviceNumData: {},
        // 当前勾选中的数据
        checkedDeviceList: []
      }
    },
    computed: {
      //默认显示省份ID
      provinceIdConfig() {
        return this.$store.state.app.provinceIdConfig
      },
      // 所有地区树形数据
      regionDataOptions() {
        return this.$store.state.device.regionDataOptions;
      },
      //有效的品牌，用于下拉列表
      brands() {
        return this.$store.state.device.brands || []
      },
      // 网点树形数据
      branchDataOptions() {
        return this.$store.state.device.branchDataOptions || []
      }
    },
    methods: {
      // 点击卡片自动选择筛选状态
      handleFilterDeviceStatus(deviceStatus){
        // 清空选项
        // Object.keys(this.filter.data).forEach(key => {
        //   if(key !== 'regionId'){
        //     this.filter.data[key] = undefined
        //   }
        // })
        this.filter.data.deviceStatus = deviceStatus;
        this.getList()
      },
      // 设置当前选择项的表单值
      setForm(row) {
        if (row && row.id) {
          this.checkedDeviceList = [row]
        } else {
          this.checkedDeviceList = this.tableData.filter((item,index) => item.id === this.ids[index]);
        }
      },
      // 获取各种状态设备数量
      async getCountDeploymentStatus() {
        try {
          const res = await reqGetCountDeploymentStatus({
            ...this.filter.data
          });
          this.deviceNumData = res.data;
        } catch (err) {
          console.log("reqGetCountDeploymentStatus 接口数据异常", err)
        }
      },
      // 下拉按钮
      handleCommand(command, row) {
        try {
          this[command](row);
        } catch (e) {
          console.log(`找不到调用的方法this.${command}`)
        }
      },
      /** 转换区域树形图数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.id,
          label: node.name,
          children: node.children,
        };
      },
        /** 转换分组树形图数据结构 */
     branchNormalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.branchCode,
          label: node.branchName,
          children: node.children || undefined,
        };
      },
      // 点击区域节点
      getChildrenRegion(id, options) {
        //是否还没找到，继续循环
        let going = true;
        let result = []
        let walker = (id, array) => {
          array.forEach(item => {
            if (!going) return;
            if (item['id'] === id) {
              going = false;
              result = [item];
            } else if (item['children']) {
              walker(id, item['children']);
            }
          });
        }
        walker(id, options)
        return result
      },
      /** 查询区域包含的分组管理列表 */
      getRegionGroup(regionId) {
        this.loading = true;
        listGroup({regionId}).then(res => {
          this.groupOptions = handleTree(res.rows, "id");
        }).finally(() => {
          this.loading = false;
        });
      },
      handleNodeClick(data) {
        this.filter.data.regionId = data.id;
        // 清空选择的分组
        this.getRegionGroup(data.id)
        this.getList();
      },
      // 表单提交接口相关配置
      formSubmitFunConfig() {
        return {
          addFunc: () => {
          },
          modifyFunc: () => {
          },
          pk: 'id',
          options: {
            ...this.form
          },
          cbFunc: () => {
            this.visible = false
          }
        }
      },
      /** 多选框选中数据 */
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id);
      },
      /** 查询工单列表 */
      getList() {
        // 如果点击了重置按钮，regionId被清空后，自动赋值为默认省份id
        if(!this.filter.data.regionId){
          this.filter.data.regionId = this.provinceIdConfig;
          this.$refs.regionTree.$refs.tree.setCurrentKey(this.provinceIdConfig);
        }
        // 获取列表
        this.getInit(listManager, {})
        // 获取各种状态设备数量
        this.getCountDeploymentStatus();
      },
      /** 详细按钮操作 */
      rowDetail(row) {
        this.$router.push({
          name: 'DeviceMonitoringDetail',
          query: {
            deviceId: row.deviceId
          }
        })
      },
      /** 返回设备部署页面 */
      goBack() {
        this.$router.go(-1);
      },
    },
    watch: {
      'dict.type.device_status': {
        handler(newValue) {
          // 设置设备状态选项数据
          try {
            this.filterArray.find(item => item.key === 'deviceStatus').options = newValue;
          } catch (e) {
            console.log("找不到对应表单项", e)
          }
        },
      },
      brands: {
        immediate: true,
        handler(newValue) {
          // 设置品牌选项数据
          try {
            this.filterArray.find(item => item.key === 'brandCode').options = newValue;
          } catch (e) {
            console.log("找不到对应表单项", e)
          }
        }
      },
    },
    created() {
      // 设置默认选择区域
      this.filter.data.regionId = this.provinceIdConfig;
      // 获取分组
      this.getRegionGroup(this.provinceIdConfig);
    }
  }
</script>

<style lang="scss" scoped>
  .app-container {
    display: flex;
    min-height: inherit;

    .right-wrap {
      flex: 1;
      width: 100%;
      height: 100%;
      overflow: hidden;

      .head-card-wrap {
        display: flex;
        width: 100%;
        min-width: 850px;
        margin-bottom: 20px;
        border: 1px solid #409eff;
        border-radius: 2px;
        background: #fff;
        box-shadow: 0 2px 8px -2px rgb(0, 0, 0, 10%);

        .card-item {
          position: relative;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          height: 75px;
          width: 25%;
          font-size: 16px;
          cursor: pointer;

          .name {
            display: flex;
            align-items: center;

            .circle {
              width: 12px;
              height: 12px;
              margin-right: 5px;
              border-radius: 50%;
              background: greenyellow;
            }
          }

          .value {
            margin-top: 8px;
            font-size: 20px;

            span {
              font-size: 18px;
            }
          }

          &:last-child {
            &::after {
              width: 0;
            }
          }

          &::after {
            position: absolute;
            content: '';
            right: 0;
            top: 50%;
            width: 1px;
            height: 60%;
            background: #409eff;
            transform: translateY(-50%);
          }
        }
      }
    }

  }
</style>
